import re
from django_redis import get_redis_connection
from rest_framework import serializers

from goods.models import SKU
from users import constants
from users.models import User, Address


class UserInfoSerializer(serializers.ModelSerializer):
    password2 = serializers.CharField(label='重复密码', write_only=True)
    sms_code = serializers.CharField(label='短信验证码', write_only=True)
    allow = serializers.CharField(label='同意协议', write_only=True)
    token = serializers.CharField(label='JWT token', read_only=True)

    class Meta:
        model = User
        fields = ('id', 'username', 'password', 'mobile', 'password2', 'sms_code', 'allow', 'token')

        extra_kwargs = {
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

    # 补充校验,手机号格式,手机号是否存在,两次密码是否一致,短信验证码是否正确, 是否同意协议

    def validate_username(self, value):
        if value.isdigit():
            raise serializers.ValidationError('用户名必须是数字和字母的组合')
        return value

    def validate_mobile(self, value):
        if not re.match(r'1[3-8]\d{9}', value):
            raise serializers.ValidationError('手机号格式有误')

        # 校验手机号是否存在
        count = User.objects.filter(mobile=value).count()
        if count > 0:
            raise serializers.ValidationError('手机号已经存在')

        return value

    def validate_allow(self, value):
        if value != 'true':
            raise serializers.ValidationError('请勾选同意')

    def validate(self, attrs):
        # 校验两次密码是否一致
        password = attrs['password']
        password2 = attrs['password2']

        if password != password2:
            raise serializers.ValidationError('两次密码不一致')

        # 校验短信验证码是否正确
        sms_code = attrs['sms_code']
        mobile = attrs['mobile']

        conn = get_redis_connection('verify_codes')
        real_sms_code = conn.get('sms_code_%s' % mobile)

        if real_sms_code is None:
            raise serializers.ValidationError('短信验证码过期')

        # 验证码校验
        if sms_code != real_sms_code.decode():
            raise serializers.ValidationError('短验证码错误')

        return attrs

    def create(self, validated_data):
        # 补充密码加密

        # 去除无需保存的字段
        del validated_data['password2']
        del validated_data['allow']
        del validated_data['sms_code']

        # 密码加密并保存
        user = User.objects.create_user(**validated_data)

        # 由服务器生成一个jwt token，保存用户的身份信息
        from rest_framework_jwt.settings import api_settings

        # 生成载荷
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        # 生成jwt token
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        # 给user增加属性token
        user.token = token
        return user


class EmailSeriazlier(serializers.ModelSerializer):
    """邮件发送序列化器"""

    class Meta:
        model = User
        fields = ('id', 'email')

    def update(self, instance, validated_data):
        """保存邮箱信息,发送邮件"""
        email = validated_data.get('email')
        instance.email = email
        instance.save()

        # 发邮件,邮件包含用户身份信息,对身份信息加密
        verify_url = instance.generate_vieify_email_url()

        # 发送激活邮件
        from celery_tasks.email.tasks import send_verify_email
        send_verify_email.delay(email, verify_url)

        return instance


class UserAddressSerializer(serializers.ModelSerializer):
    """地址序列化器类"""
    province_id = serializers.IntegerField(label='省id')
    city_id = serializers.IntegerField(label='市id')
    district_id = serializers.IntegerField(label='县id')
    province = serializers.StringRelatedField(label='省名称', read_only=True)
    city = serializers.StringRelatedField(label='市名称', read_only=True)
    district = serializers.StringRelatedField(label='县名称', read_only=True)

    class Meta:
        model = Address
        exclude = ('is_deleted', 'user', 'create_time', 'update_time')

    def validate_mobile(self, value):
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')
        return value

    def create(self, validated_data):
        # 添加user属性,并调用父类方法创建对象
        user = self.context['request'].user
        validated_data['user'] = user
        return super().create(validated_data)


class AddressTitleSerializer(serializers.ModelSerializer):
    """
    地址标题
    """
    class Meta:
        model = Address
        fields = ('title',)


class UserHistorySerializer(serializers.Serializer):
    """用户历史浏览记录序列化器"""
    sku_id = serializers.IntegerField(label='商品id')

    def validate_sku_id(self, value):
        try:
            sku = SKU.objects.get(id=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('商品不存在')

        return value

    def create(self, validated_data):
        # 获取链接
        connection = get_redis_connection('history')
        user = self.context['request'].user
        # 组织key
        key = 'history_%s' % user.id
        sku_id = validated_data.get('sku_id')

        # 使用redis的管道
        pl = connection.pipeline()
        # 如果存在该记录，就删除
        pl.lrem(key, 0, sku_id)

        # 左侧插入
        pl.lpush(key, sku_id)

        # 只保留五个
        pl.ltrim(key, 0, constants.USER_BROWSING_HISTORY_COUNTS_LIMIT-1)

        pl.execute()

        return validated_data


class UserHistoryAcquireSerializer(serializers.ModelSerializer):
    # 历史浏览记录获取序列化器

    class Meta:
        model = SKU
        fields = ('id', 'name', 'price', 'default_image_url', 'comments')